package com.hnyc.shopee;

import com.alibaba.fastjson2.JSONObject;
import com.hnyc.config.ShopeeConfig;

import com.hnyc.facade.domain.shopee.GoodsListReq;
import com.hnyc.entity.shopee.ProductItemListParam;
import com.hnyc.entity.shopee.ShopInfo;
import com.hnyc.token.TokenCache;
import com.ruoyi.common.utils.HttpParamsUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @auther zero
 * @date 2023/3/19
 **/
@Component
@Slf4j
public class ShopeeClientV2 {
    @Resource
    ShopeeConfig shopeeConfig;
    @Resource
    TokenCache tokenCache;


    OkHttpClient client ;

    @PostConstruct
    public void addInterceptor() {
        client = new OkHttpClient.Builder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .callTimeout(30, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request req = chain.request();
                log.info(req.url().encodedQuery());
                JSONObject reqParam = getRequestParams4Get(req.url());
                long partnerId = shopeeConfig.getPartnerId();
                reqParam.put("partner_id", partnerId);
                Long shopId = reqParam.getLong("shop_id");
                String accessToken = tokenCache.getShopAccessToken(shopId);
                reqParam.put("access_token", accessToken);
                long timest = ShopeeUtils.timest();
                reqParam.put("timestamp", timest);
                reqParam.put("sign", ShopeeUtils.shopSign(req.url().uri().getPath(), timest, partnerId,accessToken, shopId, shopeeConfig.getPartnerKey()));
                String oldUrl= req.url().toString();


                return chain.proceed(req.newBuilder()
                        .url(oldUrl.replace(req.url().query(), HttpParamsUtil.toQuery(reqParam)))
                        .build());
            }

            private JSONObject getRequestParams4Get(HttpUrl url) {

                JSONObject requestJson = new JSONObject();
                for (String paramKey : url.queryParameterNames()) {
                    String paramValue = url.queryParameter(paramKey);//.getQueryParameter(paramKey);
                    requestJson.put(paramKey, paramValue);
                }
                return requestJson;
            }

        }).build();;
    }

    public ShopInfo getShopInfo(long shopId) {
        String path = "/api/v2/shop/get_shop_info";
        String url = String.format("%s%s?shop_id=%s", shopeeConfig.getHost(), path, shopId);
        Request req = new Request.Builder()
                .url(url)
                .get()
                .build();

        try {
            Response execute = client.newCall(req).execute();
            log.info("[{}]{}", execute.code(), execute.message());
            ShopInfo shopInfo = JSONObject.parseObject(new String(execute.body().bytes()), ShopInfo.class);
            shopInfo.setId(shopId);
            log.info("{}", shopInfo);
            return shopInfo;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public String goodsList(GoodsListReq params){


        Request req = new Request.Builder()
                .url(String.format("%s?%s",new ProductItemListParam().url(),HttpParamsUtil.objectToQuery(params)))
                .get()
                .build();

        try {
            Response execute = client.newCall(req).execute();
            log.info("[{}]{}", execute.code(), execute.message());
            String s = new String(execute.body().bytes());
            log.info("{}", s);
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //    public void get(String path,long shopId){
//        String accessToken = tokenCache.getShopAccessToken(shopId);
//        long timest = ShopeeUtils.timest();
//        long partnerId = shopeeConfig.getPartnerId();
//        String url=String.format("%s%s?partner_id=%s&timestamp&access_token=%s&shop_id=%s&sign=%s",
//                shopeeConfig.getHost(),path, partnerId,
//                timest,
//                accessToken,
//                shopId,
//                ShopeeUtils.sign(path,timest,partnerId,shopeeConfig.getPartnerKey())
//        );
//    }
    public void post() {

    }
}
